package io.github.lee.jel.ui.folder

import android.content.res.Configuration
import android.graphics.Color
import android.os.Bundle
import android.util.TypedValue
import androidx.appcompat.widget.Toolbar
import androidx.core.content.res.ResourcesCompat
import androidx.core.os.bundleOf
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup
import androidx.recyclerview.widget.RecyclerView
import com.fondesa.recyclerviewdivider.dividerBuilder
import dagger.hilt.android.AndroidEntryPoint
import io.github.lee.core.ui.BaseRefreshFragment
import io.github.lee.core.ui.databinding.ToolbarSimpleCenterTitleBinding
import io.github.lee.core.util.getArgumentParcelable
import io.github.lee.core.util.getColor
import io.github.lee.core.util.getDrawable
import io.github.lee.core.util.toPx
import io.github.lee.jel.R
import io.github.lee.jel.domain.po.JellyfinSession
import io.github.lee.jel.ui.item.list.ItemListActivity
import io.github.lee.jel.utils.screenWidthDP

@AndroidEntryPoint
class MediaFolderFragment : BaseRefreshFragment<MediaFolderVM>() {

    companion object {
        private const val KEY_SESSION = "SESSION"
        fun newInstance(session: JellyfinSession): MediaFolderFragment {
            val fragment = MediaFolderFragment()
            fragment.arguments = bundleOf(KEY_SESSION to session)
            return fragment
        }
    }

    override fun onCreateToolbar(): Toolbar =
        ToolbarSimpleCenterTitleBinding.inflate(layoutInflater)
            .apply {
                bg = Color.WHITE
                title = getArgumentParcelable(KEY_SESSION, JellyfinSession::class.java)?.name
                    ?: getString(R.string.txt_my_media)
                titleColor = ResourcesCompat.getColor(resources, R.color.main_black, null)
            }
            .toolbar

    //===Desc:=============================================================
    override fun onCreateViewModel(): MediaFolderVM =
        viewModels<MediaFolderVM>().value.also {
            it.sessionId = getArgumentParcelable(KEY_SESSION, JellyfinSession::class.java)?.userId
        }


    override fun onCreateLayoutManager(): RecyclerView.LayoutManager =
        GridLayoutManager(mContext, if (screenWidthDP(mContext) > 600) 3 else 2)
            .apply {
                spanSizeLookup = object : SpanSizeLookup() {
                    override fun getSpanSize(position: Int): Int {

                        return if (position == ((mAdapterHelper?.adapter?.adapters?.size
                                ?: 0) + (vm?.adapter?.items?.size ?: 0) - 1) - 1
                        ) {
                            spanCount
                        } else {
                            1
                        }
                    }

                }
            }


    //===Desc:=============================================================

    override fun onInitData(savedInstanceState: Bundle?) {
        super.onInitData(savedInstanceState)
        enableLoadMore = false
    }

    override fun onSetViewListener() {
        super.onSetViewListener()
        vm?.adapter?.setOnItemClickListener { _, _, position ->
            val item = vm?.adapter?.getItem(position)
            if (null == item) {
                toast(getString(R.string.error_application_error))
                return@setOnItemClickListener
            }
            ItemListActivity.start(mContext, item)
        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        val lm = recyclerView?.layoutManager
        if (lm is GridLayoutManager) {
            lm.spanCount = if (screenWidthDP(mContext) > 600) 3 else 2
        }
        (0 until (recyclerView?.itemDecorationCount ?: 0)).forEach {
            recyclerView?.removeItemDecorationAt(it)
        }
        addItemDecoration(
            mContext.dividerBuilder()
                .color(Color.TRANSPARENT)
                .size(8, TypedValue.COMPLEX_UNIT_DIP)
                .build()
        )

    }

    override fun onSetViewData() {
        super.onSetViewData()
        val d = getDrawable(R.drawable.outline_arrow_back_ios_new_24)
        d?.setTint(getColor(R.color.main))
        setNavigationIcon(d) { activity?.finish() }

        recyclerView?.setPadding(8.toPx(mContext), 0, 8.toPx(mContext), 0)
        addItemDecoration(
            mContext.dividerBuilder()
                .color(Color.TRANSPARENT)
                .size(8, TypedValue.COMPLEX_UNIT_DIP)
                .build()
        )
    }
}